<template>
	<view class="content">
		<view class="nav">
			<view v-for="(item, index) in category" @click="SwitchVariety(index)" :key="index"
				:class="{ active: activeIndex === index }" style="cursor: pointer">{{ item }}</view>
		</view>
		<view class="cont">
			<view class="item">
				<!-- 基础表单校验 -->
				<uni-forms :modelValue="form" ref="valiForm" label-width="120px" label-position="top"
					v-if="activeIndex == 0">
					<uni-forms-item label="输入手机号" required name="username">
						<uni-easyinput v-model.number="form.username" placeholder="请输入手机号" />
					</uni-forms-item>
					<uni-forms-item label="输入旧密码" required name="oldpassword">
						<uni-easyinput v-model.trim="form.oldpassword" placeholder="请输入旧密码" />
					</uni-forms-item>
					<uni-forms-item label="输入新密码" required name="newpassword">
						<uni-easyinput type="password" v-model.trim="form.newpassword" placeholder="请输入新密码" />
					</uni-forms-item>
					<uni-forms-item label="再次输入新密码" required name="newagianpassword">
						<uni-easyinput type="password" v-model.trim="form.newagianpassword" placeholder="请再次输入新密码" />
					</uni-forms-item>
					<uni-forms-item>
						<button :loading="loading" @click="Submit('valiForm')" type="primary">提交</button>
					</uni-forms-item>
				</uni-forms>
				<!-- 手机 -->
				<uni-forms :modelValue="form1" ref="valiForm1" label-width="120px" label-position="top"
					v-if="activeIndex == 1">
					<uni-forms-item label="输入手机号" required name="username">
						<uni-easyinput v-model.number="form1.username" placeholder="请输入手机号" />
					</uni-forms-item>
					<uni-forms-item label="输入验证码" required name="code">
						<view class="yan">
							<uni-easyinput v-model.number="form1.code" placeholder="请输入验证码" />
							<button v-if="time" @click="sendMessage()" type="primary">发送</button>
							<button v-else type="primary">{{secend}}</button>
						</view>
					</uni-forms-item>
					<uni-forms-item type="password" label="输入新密码" required name="newpassword">
						<uni-easyinput v-model="form1.newpassword" placeholder="请输入新密码" />
					</uni-forms-item>
					<uni-forms-item type="password" label="再次输入新密码" required name="newagianpassword">
						<uni-easyinput v-model="form1.newagianpassword" placeholder="请再次输入新密码" />
					</uni-forms-item>
					<uni-forms-item>
						<button :loading="loading" @click="Submit('valiForm1')" type="primary">提交</button>
					</uni-forms-item>
				</uni-forms>
			</view>
		</view>
	</view>
</template>

<script>
	const app = getApp();
	import {
		getInquiryIDOriginal,
		getEditAction,
		RedisAdd,
		isPhoneCode
	} from "@/api/global.js";
	export default {
		data() {
			return {
				loading: false,
				activeIndex: 0,
				timer: null,
				time: true,
				secend: 60,
				RandomCode: '',
				category: [
					//用户专区分类筛选
					"旧密码验证",
					"手机号验证",
				],
				form: {
					username: "", //15146557172
					oldpassword: "", //a123456
					url: "/pages/index/index",
					newpassword: '',
					newagianpassword: '',
					type: "true",
					code: '',
				},
				form1: {
					username: "", //15146557172
					url: "/pages/index/index",
					newpassword: '',
					newagianpassword: '',
					type: "true",
					code: '',
				},
				UserInfo: {},
				rules: {
					username: {
						rules: [{
							required: true,
							errorMessage: '手机号不能为空'
						}, {
							format: 'number',
							errorMessage: '手机号只能输入数字'
						}, {
							validateFunction: function(rule, value, data, callback) {
								let iphoneReg = /^1[3-9]\d{9}$/
								if (!iphoneReg.test(value)) {
									callback('手机号码格式不正确，请重新填写')
								}
								return true
							}
						}]
					},
					oldpassword: {
						rules: [{
							required: true,
							errorMessage: '旧密码不能为空'
						}]
					},
					newpassword: {
						rules: [{
							required: true,
							errorMessage: '新密码不能为空'
						}, {
							minLength: 6,
							maxLength: 10,
							errorMessage: '新密码应为6到11位字符'
						}]
					},
					newagianpassword: {
						rules: [{
							required: true,
							errorMessage: '再次输入的新密码不能为空'
						}, {
							minLength: 6,
							maxLength: 10,
							errorMessage: '新密码应为6到11位字符'
						}]
					},
					code: {
						rules: [{
							required: true,
							errorMessage: '短信验证码不能为空'
						}, {
							format: 'number',
							errorMessage: '短信验证码只能输入数字'
						}]
					},
				},
			};
		},
		onReady() {
			this.$refs.valiForm.setRules(this.rules)
		},
		onLoad() {
			this.form.username = uni.getStorageSync('use')
			this.form1.username = uni.getStorageSync('use')
		},
		methods: {
			async SwitchVariety(index) {
				this.activeIndex = index;
			},
			async getEdit(data) {
				const res = await getEditAction({
					data
				})
				this.loading = false
				if (res.redirect && res.redirect == 'REDIRECT') {
					uni.navigateTo({
						url: '/pages/My/Login'
					})
				} else if (res.Status == 'success') {
					uni.removeStorage({
						key: 'token',
						success() {
							console.log('已清除')
						}
					})
					uni.removeStorage({
						key: 'password',
						success() {
							console.log('已清除')
						}
					})
					uni.removeStorage({
						key: 'username',
						success() {
							console.log('已清除')
						}
					})
					uni.removeStorage({
						key: 'client',
						success() {
							console.log('已清除')
						}
					})
					uni.showToast({
						title: '修改成功!,两秒后返回登录页',
						icon: 'success',
						success() {
							setTimeout(() => {
								uni.navigateTo({
									url: '/pages/My/Login'
								})
							}, 2000)
						}
					})
				}
			},
			sendMessage() {
				if (this.form1.username == '') {
					uni.showToast({
						title: '请先输入正确的手机号再点击发送',
						icon: 'none'
					})
					return
				}
				const reg = /^1[3-9]\d{9}$/
				if (!reg.test(this.form1.username)) {
					uni.showToast({
						title: '请检查手机号格式是否正确',
						icon: 'none'
					})
					return
				}
				this.time = false
				this.secend = 60
				this.secend--
				this.timer = setInterval(() => {
					if (this.secend == '01') {
						clearInterval(this.timer)
						this.time = true
						return
					}
					this.secend--
					if (this.secend < 10) {
						this.secend = '0' + this.secend
					}
				}, 1000)
				let code = '';
				for (let i = 0; i < 6; i++) {
					code += parseInt(Math.random() * 10);
				}
				this.RandomCode = code
				uniCloud.callFunction({
					name: 'sendSms', //对应的云函数名
					data: {
						phone: this.form1.username,
						data: {
							name: '众菌联',
							code: this.RandomCode, //随机生成的验证码，如123456
							action: '注册', //校验类型为“注册”
							expMinute: '5', //短信的有效期，5分钟
						}
					}
				}).then(res => {
					if (res.success) {
						uni.showToast({
							title: '短信已发送',
							icon: 'none'
						})
						this.RedisPush()
					}
				}).catch(msg => {
					uni.showToast({
						title: '系统错误!请稍后重试',
						icon: 'none'
					})
				});
			},
			async RedisPush() {
				const res = await RedisAdd({
					data: {
						Key: 'zjl_' + this.form1.username,
						Main: JSON.stringify({
							code: this.RandomCode,
							expires_in: parseInt(new Date().getTime() / 1000) + 300
						}),
						Expire: 300,
					}
				})
				console.log(res)
			},
			async CheckCode(data) {
				const res = await isPhoneCode({
					data
				})
				if (res.Status == 'success') {
					let Data = {
						Data: JSON.stringify({
							Modify: {
								system_user_info: [this.UserInfo]
							}
						}),
						token: uni.getStorageSync('token'),
					}
					this.getEdit(Data)
				} else {
					uni.showToast({
						title: '短信验证码有误!',
						icon: 'none'
					})
					this.loading = false
				}
			},
			async getOriginal(data) {
				console.log(1);
				const res = await getInquiryIDOriginal({
					data
				})
				if (this.activeIndex == 0 && this.form.oldpassword != res[0].Pass_Ward) {
					uni.showToast({
						title: '您输入的旧密码有误!',
						icon: 'none'
					})
					this.loading = false
					return
				}
				if (this.activeIndex == 1 && this.form1.newpassword == res[0].Pass_Ward) {
					uni.showToast({
						title: '您输入的新密码与旧密码重复,请重新输入新密码!',
						icon: 'none'
					})
					this.loading = false
					return
				}
				if (this.activeIndex == 0) {
					res[0].Pass_Ward = this.form.newpassword
					this.UserInfo = res[0]
					let Data = {
						Data: JSON.stringify({
							Modify: {
								system_user_info: [this.UserInfo]
							}
						}),
						token: uni.getStorageSync('token'),
					}
					this.getEdit(Data)
				} else {
					res[0].Pass_Ward = this.form1.newpassword
					this.UserInfo = res[0]
					let Data = {
						Code: this.form1.code,
						Phone: this.form1.username
					}
					this.CheckCode(Data)
				}
			},
			Submit(formName) {
				this.$refs[formName].setRules(this.rules)
				uni.showLoading({
					title: '提交中...'
				})
				this.$refs[formName].validate().then(res => {
					uni.hideLoading()
					if (this.activeIndex == 0) {
						if (this.form.oldpassword == this.form.newpassword) {
							uni.showToast({
								title: '新密码不能与旧密码相同!',
								icon: 'none'
							})
							return
						}
						if (this.form.newpassword != this.form.newagianpassword) {
							uni.showToast({
								title: '两次输入的新密码不同!',
								icon: 'none'
							})
							return
						}
						// this.loading = true
						if (!this.loading) {
							this.loading = true
							let data = {
								Primary_Key_Name: 'User_Number', //主键名
								Primary_Key: this.form.username, //主键值
								Data: 'system_user_info',
								token: uni.getStorageSync('token'),
							}
							this.getOriginal(data)
						}
					} else {
						if (this.time) {
							uni.showToast({
								title: '请点击发送获取短信验证码',
								icon: 'none'
							})
							return
						}
						if (this.form1.newpassword != this.form1.newagianpassword) {
							uni.showToast({
								title: '两次输入的新密码不同!',
								icon: 'none'
							})
							return
						}
						if (!this.loading) {
							this.loading = true
							let data = {
								Primary_Key_Name: 'User_Number', //主键名
								Primary_Key: this.form1.username, //主键值
								Data: 'system_user_info',
								token: uni.getStorageSync('token'),
							}
							this.getOriginal(data)
						}
					}
				}).catch(err => {
					uni.hideLoading()
					console.log('表单错误信息：', err);
				})
			}
		},
	};
</script>

<style lang="scss">
	.content {
		background-color: #f5f5f5;
		height: calc(100vh);
		width: 100%;

		.nav {
			height: 88rpx;
			background-color: #fff;
			display: flex;
			align-items: center;
			justify-content: space-around;

			// font-weight: bold;
			view {
				text-align: center;
				height: 100%;
				display: flex;
				align-items: center;
				font-size: 30rpx;
				padding: 10rpx;
				box-sizing: border-box;
			}

			.active {
				border-bottom: 3px solid #28a745;
				font-size: 30rpx;
			}
		}

		.cont {
			width: 100%;
			padding: 20rpx;
			box-sizing: border-box;

			.item {
				border-radius: 20rpx;
				background-color: #fff;
				padding: 20rpx;
				box-sizing: border-box;
				margin: 0 0 30rpx 0;
			}

			.yan {
				display: flex;
				align-items: center;

				button {
					height: 72rpx;
					line-height: 72rpx;
					font-size: 24rpx;
				}
			}

			uni-button {
				background: #28a745;
			}
		}
	}
</style>